package de.dhbw.asa.controller;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.context.RequestContext;

import de.dhbw.asa.model.Customer;


@ManagedBean
@RequestScoped
public class LoginCtrl
{

	@ManagedProperty(value = "#{customer}")
	Customer customer;
		
    public void  checkPW(ActionEvent actionEvent)
    {
    	
        RequestContext context = RequestContext.getCurrentInstance();  
        FacesMessage msg = null; 
    	
    	System.out.println("Checking password:");
    	System.out.println("CustomerNr: "+customer.getiCustomerNr());
    	System.out.println("Entered Password: "+customer.getsEnteredPassword());
    	customer.load(customer.getiCustomerNr());
    	System.out.println("Password of loaded Customer: "+customer.getsPassword());
        if(customer.getsPassword().equals(customer.getsEnteredPassword()))
        {
        	customer.setbLoggedIn(true);
        	msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", customer.getsForename());  
        	//return "products";
        }
        else
        {
        	customer.setbLoggedIn(false);
        	 msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Falsche Anmeldedaten. Bitte versuchen Sie es erneut.");
        	//return "failure";
        }
        FacesContext.getCurrentInstance().addMessage(null, msg);  
        context.addCallbackParam("loggedIn", customer.isbLoggedIn());  
    }
    
    public String checkLogin()
    {
    
    	String sReturn="failure";
        RequestContext context = RequestContext.getCurrentInstance();  
        FacesMessage msg = null; 
    	
    	if(customer.isbLoggedIn())
        {
        	//here nothing should happen
    		sReturn="processOrder";
        }
        else
        {
        	 msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Sie sind nicht eingeloggt. Bitte loggen Sie sich ein oder registrieren Sie sich.");
             FacesContext.getCurrentInstance().addMessage(null, msg);  
             context.addCallbackParam("loggedIn", customer.isbLoggedIn());
        	 //return "failure";
        } 
        return sReturn;
    }
    
    public void logout()
    {
    	//We want to log out the customer
    	customer.setbLoggedIn(false);
    }

	public Customer getCustomer() 
	{
		return customer;
	}

	public void setCustomer(Customer customer) 
	{
		this.customer = customer;
	}

}
